package com.yzy.soft.system.controller;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.google.common.collect.Lists;
import com.yzy.soft.common.persistence.dao.MetadataDatabaseMapper;
import com.yzy.soft.common.persistence.model.MetadataDatabase;
import com.yzy.soft.core.base.controller.BaseController;
import com.yzy.soft.core.base.tips.ErrorTip;
import com.yzy.soft.core.base.tips.Tip;
import com.yzy.soft.system.dto.TableDataDto;
import com.yzy.soft.system.freemarker.SynchronousMetadata;
import com.yzy.soft.system.service.IMetadataDatabaseService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.session.RowBounds;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.Date;
import java.util.List;

//import com.yzy.soft.system.dto.MetadataDatabaseDto;

/**
 * 描述：测试控制层
 *
 * @author Yinzhiyuan
 * @date 2018-12-19 01:44:11
 */
@Api(value = "测试控制层")
@RestController
@RequestMapping("/metadatadatabase")
public class MetadataDatabaseController extends BaseController {

    private final static Logger logger= LoggerFactory.getLogger(MetadataDatabaseController.class);

    @Autowired
    private IMetadataDatabaseService metadataDatabaseService;

    @Autowired
    private MetadataDatabaseMapper metadataDatabaseMapper;

    @Autowired
    private SynchronousMetadata synchronousMetadata;

    /**
     * 描述：查询 测试列表
     */
    @ApiOperation(value = "查询测试")
    @GetMapping(value = "/page/{id}", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public TableDataDto getAll(@RequestParam(name = "page", defaultValue = "1", required = true) int page, @RequestParam(name = "limit", defaultValue = "10", required = true) int pageSize) throws Exception {

        Wrapper<MetadataDatabase> metadataDatabase = new EntityWrapper<MetadataDatabase>();
        page = (page - 1) * pageSize;
        pageSize = page + pageSize;
        List<MetadataDatabase> result = metadataDatabaseMapper.selectPage(new RowBounds(page, pageSize), metadataDatabase);
        TableDataDto tableDataDto = new TableDataDto();
        tableDataDto.setCode("00");
        tableDataDto.setMsg("000");
        tableDataDto.setCount(metadataDatabaseMapper.selectCount(metadataDatabase));
        tableDataDto.setData(result);
        return tableDataDto;
    }

    /**
     * 描述：根据Id 查询 测试
     *
     * @param id 测试id
     */
    @ApiOperation(value = "查询测试")
    @GetMapping(value = "/{id}", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public MetadataDatabase findById(@PathVariable("id") String id) throws Exception {
        return metadataDatabaseMapper.selectById(id);
    }

    /**
     * 描述：根据用户Id 下拉框要选择的数据库
     *
     * @param id 测试id
     */
    @ApiOperation(value = "查询测试")
    @GetMapping(value = "/dropDownDatabase", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public List<MetadataDatabase> selectDropDownDatabaseByUserId() throws Exception {
        return metadataDatabaseMapper.selectDropDownDatabaseByUserId();
    }

    /**
     * 描述:创建测试
     *
     * @param metadataDatabaseDTO 测试DTO
     */
    @ApiOperation(value = "创建测试")
    @PostMapping(value = "" )
    public Tip create(@ModelAttribute MetadataDatabase metadataDatabase) {
        logger.info("MetadataDatabaseController create:{}",metadataDatabase);
        metadataDatabase.setCreatetime(new Date());
        metadataDatabase.setLastupdatetime(new Date());
        Integer result = metadataDatabaseMapper.insert(metadataDatabase);
        return SUCCESS_TIP;
    }

    /**
     * 描述：删除测试
     *
     * @param id 测试id
     */
    @ApiOperation(value = "删除测试")
    @DeleteMapping("/{id}")
    public Tip delete(@RequestParam(name = "ids[]", required = false) Integer[] metadataDatabase, @PathVariable(name = "id", required = false) Integer id) {
        //Collections.<String>
        logger.info("MetadataDatabaseController delete: {}-------{}", Arrays.toString(metadataDatabase),id);
        if (null !=id) {
            Integer result = metadataDatabaseMapper.deleteById(id);
        } else if (metadataDatabase.length != 0) {
            Integer result = metadataDatabaseMapper.deleteBatchIds(Lists.newArrayList(metadataDatabase));
        }
        return SUCCESS_TIP;
    }

    @ApiOperation(value = "批量删除测试")
    @DeleteMapping(value = "/",produces = MediaType.APPLICATION_JSON_UTF8_VALUE )
    public Tip delete1(@RequestParam(name = "ids", required = false) Integer[] ids) {
//    public Tip delete1(@RequestBody int[] ids) {
        logger.info("MetadataDatabaseController delete1 批量删除测试: {}", Arrays.toString(ids));
        if (ids.length != 0) {
            Integer result = metadataDatabaseMapper.deleteBatchIds(Lists.newArrayList(ids));
        }
        return SUCCESS_TIP;
    }


    /**
     * 描述：更新测试
     *
     * @param id 测试id
     */
    @ApiOperation(value = "更新测试")
    @PutMapping(value = "", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public Tip updateMetadataDatabase(@ModelAttribute MetadataDatabase metadataDatabase) throws Exception {
        metadataDatabase.setLastupdatetime(new Date());
        Integer result = metadataDatabaseMapper.updateById(metadataDatabase);
        return SUCCESS_TIP;
    }

    @GetMapping("/by")
    public TableDataDto getCadtion(@ModelAttribute MetadataDatabase metadataDatabase) {
        Wrapper<MetadataDatabase> wrapper = new EntityWrapper<MetadataDatabase>();
        wrapper.where("company_id={0}", metadataDatabase.getCompanyId());
        List<MetadataDatabase> result = metadataDatabaseMapper.selectList(wrapper);
        TableDataDto tableDataDto = new TableDataDto();
        tableDataDto.setCode("00");
        tableDataDto.setMsg("000");
        tableDataDto.setCount(result.size());
        tableDataDto.setData(result);
        return tableDataDto;
    }

    @PutMapping("/status/{id}")
    public Tip status(@PathVariable("id") Integer id) {
        Integer result = metadataDatabaseMapper.status(id);
        if (null == result) {
            return new ErrorTip(500, "s");
        }
        return SUCCESS_TIP;
    }

    @GetMapping("/metadataDatabaseId/{metadataDatabaseId}")
    public TableDataDto getbyAccountId(@PathVariable(name = "metadataDatabaseId") String metadataDatabaseId, @RequestParam(name = "page", defaultValue = "1", required = true) int page, @RequestParam(name = "limit", defaultValue = "10", required = true) int pageSize) {
        Wrapper<MetadataDatabase> metadataDatabaseWrapper = new EntityWrapper<>();
        metadataDatabaseWrapper.where("accountid={0}", metadataDatabaseId);
        page = (page - 1) * pageSize;
        pageSize = page + pageSize;
        List<MetadataDatabase> result = metadataDatabaseMapper.selectPage(new RowBounds(page, pageSize), metadataDatabaseWrapper);
        TableDataDto tableDataDto = new TableDataDto();
        tableDataDto.setCode("00");
        tableDataDto.setMsg("000");
        tableDataDto.setCount(metadataDatabaseMapper.selectCount(metadataDatabaseWrapper));
        tableDataDto.setData(result);
        return tableDataDto;
    }

    @ApiOperation("批量将费用归档设置成弃用状态")
    @PostMapping("/batchNuUse")
    public Tip batchNuUse(@RequestParam(name = "ids[]", required = false) Integer[] metadataDatabase) {
        if (metadataDatabase.length != 0) {
            Integer result = metadataDatabaseMapper.batchNuUseIds(Lists.newArrayList(metadataDatabase));
        }
        return SUCCESS_TIP;
    }

    @ApiOperation("批量将费用归档设置成可用状态")
    @PostMapping("/batchUse")
    public Tip batchUse(@RequestParam(name = "ids[]", required = false) Integer[] metadataDatabase) {
        if (metadataDatabase.length != 0) {
            Integer result = metadataDatabaseMapper.batchUseIds(Lists.newArrayList(metadataDatabase));
        }
        return SUCCESS_TIP;
    }

    @ApiOperation("同步数据库信息")
    @GetMapping("/synchronous/{id}")
    public Tip synchronous(@PathVariable("id") Integer id) {
//        SynchronousMetadata synchronousMetadata=new SynchronousMetadata();
        synchronousMetadata.synchronousMetadataDatabase(id);
//        if(null==result){
//            return new ErrorTip(500,"s");
//        }
        return SUCCESS_TIP;
    }

    @ApiOperation("同步数据库信息")
    @GetMapping("/synchronous")
    public Tip synchronousAll() {
//        SynchronousMetadata synchronousMetadata=new SynchronousMetadata();
        synchronousMetadata.synchronousMetadataDatabase();
//        if(null==result){
//            return new ErrorTip(500,"s");
//        }
        return SUCCESS_TIP;
    }



    @ApiOperation("同步数据库信息")
    @PostMapping("/connectTest")
    public Tip connectTest(@ModelAttribute MetadataDatabase metadataDatabase) {
        if (synchronousMetadata.connectTest(metadataDatabase)) {
            return SUCCESS_TIP;
        }
        return new ErrorTip(500, "s");
    }
}